import $service from '../../../service';
var that;
var siteId;
const app = getApp();
Page({
  data: {
    params: {
      userName:"", //收货人
      userPhone:"", // 电话号码
      addressDetl:"", //详细地址
      addressDeft: '0', //是否是默认地址
      userId: '',
      address: ''
    },
    switchChecked: false,
    region: ['广东省', '广州市', '海珠区'],
  },
  onLoad: function (e) {
    siteId = e.id;
    if (siteId){
      this.getReceivingAddressInfo()
      wx.setNavigationBarTitle({
        title: '修改收货地址'
      })
    }
  },
  onShow: function () {
    that = this.data;
    that.params.userId = JSON.parse($service.getStore('userInfo')).id;
  },
  // 获取地址详情
  getReceivingAddressInfo() {
    app.http.getReceivingAddressInfo({id: siteId}).then(res => {
      let region = res.data.address.split(' ');
      let switchChecked = res.data.addressDeft === '1' ? true : false
      this.setData({
        params: res.data,
        region,
        switchChecked
      })
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  // 默认收货地址
  switch1Change:function(e){
    this.setData({
      "params.addressDeft": e.detail.value ? '1' : '0'
    })
  },
  // 所在地区
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
  //监听input
  inputChange(e){
     var val = e.detail.value;
     var index = e.currentTarget.dataset.index;
     if (index == 0){
      that.params.userName = val;
    } else if (index == 1){
      that.params.userPhone = val;
    } else if (index == 2){
      that.params.addressDetl = val;
    } 
  },
  // 检查地址数量
  getReceivingAddress(){
    let params = { 
      current: 1,
      size: 20
    }
    app.http.getReceivingAddress(params).then(res => {
      if (res.data.total <= 20) {
        this.save_add();
      } else {
        $service.showToast('你的地址数量已达上限')
      }
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  // 保存&修改新增地址
  save_add(){
    if ($service.isUndefinedAndEmpty(that.params.userName)) {
      $service.showToast('请输入名称');
      return;
    }
    if ($service.isUndefinedAndEmpty(that.params.userPhone)) {
      $service.showToast('请输入手机号');
      return;
    }
    if (!$service.validateElement('mobile', that.params.userPhone)){
      $service.showToast('请输入正确手机号');
      return;
    }
    if ($service.isUndefinedAndEmpty(that.params.addressDetl)) {
          $service.showToast('请输入详细地址');
      return;
    }
    that.params.address = that.region[0] + " " +that.region[1]+" "+that.region[2]
    let interfaceName = siteId ? 'updateReceivingAddress' : 'addReceivingAddress'
    app.http[interfaceName](that.params).then(res => {
      $service.showToast(res.msg)
      setTimeout(function(){
        wx.navigateBack()
      },1000)
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
})